<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
error_reporting(E_ERROR | E_WARNING | E_PARSE);

//分页条数
define('config_limit','12');
//分页条数选项
define('config_limits','[12,20,30,40]');



use think\Db;
use think\Request;
use think\Session;
use think\Controller;

//获取用户信息   $code  通过微信返回的code
       function getUserInfo($code)
    {
        $website=website();
        $appid =  $website['appid'];
        $appsecret = $website['appsecret'];

        //Get access_token
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $access_token_json = https_request($access_token_url);//自定义函数
        $access_token_array = json_decode($access_token_json,true);//对 JSON 格式的字符串进行解码，转换为 PHP 变量，自带函数
        //获取access_token
        $access_token = $access_token_array['access_token'];//获取access_token对应的值
        //获取openid
        $openid = $access_token_array['openid'];//获取openid对应的值

        //Get user info
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
        $userinfo_json = https_request($userinfo_url);
        $userinfo_array = json_decode($userinfo_json,ture);
        return $userinfo_array;
    }
//CURL 提交信息（get方法）    $url  提交链接
    function https_request($url)//自定义函数,访问url返回结果
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl,  CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)){
            return 'ERROR'.curl_error($curl);
        }
        curl_close($curl);
        return $data;
    }



//数据库获取用户信息   $id  用户ID
    function get_user($id){
        $userinfo=Db::name("user")->find($id);
        $userinfo['wxname']=base64_decode($userinfo['username']);
        return $userinfo;
    }
    function get_user_openid($openid){
        $userinfo=Db::name("user")->where(array('openid' =>$openid))->find();
        return $userinfo;
    }
//基本设置
    function website(){
        $config=Db::name("config")->select();
        foreach ($config as $k => $v) {
            $website[$v['name']]=$v['value'];
        }
        return $website;
    }
//从数据库获取积分，如果数据库没有就从ERP获取的同时写入数据库
    function tel_get_integral($tel){
        $user_integral=Db::name('user_integral');
        $info=$user_integral->where('tel',$tel)->find();
        if($info){
            return $info['integral'];
        }else{
            $info=erp_active($tel);
            $info=json_decode($info,true);
            $user_integral->insert(array('tel' =>$tel,'integral'=>$info['integral']));
            return $info['integral'];
        }
    }



//条形吗
    function barcode($key){
        return "http://www.sxjhol.vip/public/barcodegen/test_1D.php?text=".$key;
    }
//二维码
    function qrcode($key){
        $url='http://www.sxjhol.vip/public/phpqrcode/index.php?data='.$key;
        $qr=https_request($url);
        $qrurl='/public/phpqrcode/temp/'.$qr;
        return $qrurl;
    }
//判断是否超级管理员
    function is_super_master(){
        $master=SESSION::get('cmuser');
        $master_info=Db::name('admin')->where('master',$master)->find();
        return $master_info['ini'];
    }



//批量获取粉丝
       function getUsers($openid)
    {

        $website=website();
        $appid =  $website['appid'];
        $appsecret = $website['appsecret'];

        $access_token=get_token();


        $access_token_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $access_token_json = https_request($access_token_url);//自定义函数
        $usersinfo = json_decode($access_token_json,true);//对 JSON 格式的字符串进行解码，转换为 PHP 变量，自带函数

        return $usersinfo;


    }
//批量获取粉丝end



//获取access_token  超过7200秒自动重新获取同时写入数据库
    function get_token(){
        $website=website();
        $token=explode('|',$website['access_token']);
        $check=time()-$token[0];
        if($check > 7200){
            $appid = $website['appid'];
            $appsecret = $website['appsecret'];
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
            $data_json=https_request($url);
            $data=json_decode($data_json,true);
            $access_token=$data['access_token'];
            $where['name']='access_token';
            $save['value']=time().'|'.$access_token;
            Db::name('config')->where($where)->update($save);
        }else{
            $access_token=$token[1];
        }
        return $access_token;
    }


//CURL 提交信息（post方法）    $url  提交链接   $data 提交的数据（数组）
    function curl_post($url , $data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    //微信变动发送提醒  $data 提醒数据  $openid  微信openid  $template_id  消息模板的ID
    function send_wx($data,$openid,$template_id,$url='')
    {

        $template_msg=array(
            'touser'=>$openid,
            'template_id'=>$template_id,
            'topcolor'=>'#FF0000',
            'data'=>$data
            );
        if($url){
            $template_msg['url']=$url;
        }
        $send=json_encode($template_msg);
        $get_token=get_token();
        $url='https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$get_token;
        $info=curl_post($url,$send);

        return $info;
    }


//发送短信
function sendsns($telphone)
    {
        $config=Db::name("config")->select();
        foreach ($config as $k => $v) {
            $website[$v['name']]=$v['value'];
        }


        if($website['sns']==1){

            $url='http://api.1cloudsp.com/api/v2/single_send';

            //生成验证码
            $rand=rand(1000,9999);

            //提交的数据
            $post_data = array(
                "accesskey" => $website['accessKey'],
                "secret" => $website['secret'],
                "sign" => $website['sign'],
                "templateId" => $website['templateId'],
                "mobile" => $telphone,
                "content" => $rand
                );
            //执行提交
            $data=curl_post($url,$post_data);

            //返回数据的处理
            $array=explode('"', $data);
            $return['code']=$array[3];//返回码
            $return['msn']=$array[7];//详情
            
            //把验证码和当前电话存入
            Session::flash('msn',$rand);
            Session::flash('telphone',$telphone);



            return $return['msn'];
        }else{
            return '短信接口关闭，请联系管理员';
        }

    }

//ERP api  对接
function erp_active($tel,$type=0,$integral=0,$openid=''){
            header("content-type:text/html;charset=utf-8");
            $url='http://1.85.57.254:9991/xbjhwxapi.ashx';
            //初始化
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL, $url);
            //设置头文件的信息作为数据流输出
            curl_setopt($curl, CURLOPT_HEADER, 1);
            //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            //设置post数据
            $post_data = array(
                "type" => $type,
                "tel" => $tel,
                "integral" => $integral,
                "openid" => $openid
                );
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
            //执行命令
            $data = curl_exec($curl);
            //关闭URL请求
            curl_close($curl);

            $array=explode('"', $data);
            $return['code']=$array[3];
            $return['msg']=$array[7];
            $return['tel']=$array[13];
            $cl=explode(":",$array[16]);
            $cl=explode("}",$cl[1]);
            $return['integral']=$cl[0];
            $return=json_encode($return);
            return $return;

}



//栏目无限级
function column($id=0,$level=1){
    $colunm=array();
    $where['pid']=$id;
    $col=Db::name('column')->where($where)->select();
    foreach ($col as $key => $value) {
        $colunm[]=$value;
        $cha=column($value['id']);
        if($cha){
            $level++;
            foreach ($cha as $k => $v) {
                $colunm[]=$v;
            }
        }
    }
    return $colunm;
}







//检测是否登录和是否绑定手机
function check_login(){
    $openid=SESSION::get('wechat_user');
    $userDb=Db::name('user');
    $user=$userDb->where(array('openid'=>$openid))->find();
    if(!$user){
        return '0';
    }else if(!$user['telphone']){
        return '10';
    }
}
//写入日志
function set_log($user,$content){
    $log=Db::name('log');
    $data['user']=$user;
    $data['time']=date('Y-m-d H:i:s',time());
    $data['content']=$content;
    $log -> insert($data);
}








//返回码
function return_code($code){
    $data=array();
    $data['code']=$code;
    if($code==10000){
        $data['msg']='操作成功';
    }else if($code==10010){
        $data['msg']='拒绝访问';
    }else if($code==10020){
        $data['msg']='JSON格式错误';
    }else if($code==10030){
        $data['msg']='缺乏手机号';
    }else if($code==10040){
        $data['msg']='操作类型有误！';
    }else if($code==10050){
        $data['msg']='操作类型为空！';
    }else if($code==10060){
        $data['msg']='缺乏操作积分';
    }else if($code==10070){
        $data['msg']='操作积分格式错误';
    }else if($code==10080){
        $data['msg']='缺乏订单号';
    }else if($code==10090){
        $data['msg']='订单号格式错误';
    }else if($code==10100){
        $data['msg']='请勿重复操作';
    }
    $data=json_encode($data,JSON_UNESCAPED_UNICODE);
    return $data;
}



















function isMobile()
{
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    if (isset($_SERVER['HTTP_VIA'])) {
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile');
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}
/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }
    return $counter;
}
/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }
    return $list;
}
/**
 * 构建层级（树状）数组
 * @param array  $array          要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }
    return $tree;
}
/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name])) {
                $item[$child_key_name] = [];
            }

            $item[$child_key_name][] = $child;
        }
    }
    return $parent;
}
/**
 * 手机号格式检查
 * @param string $mobile
 * @return bool
 */
function check_mobile_number($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    $reg = '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#';

    return preg_match($reg, $mobile) ? true : false;
}

function check_env(){
    $items = array(
        'os'      => array('操作系统', '不限制', '类Unix', PHP_OS, 'check'),
        'php'     => array('PHP版本', '5.5', '5.5+', PHP_VERSION, 'check'),
        'upload'  => array('附件上传', '不限制', '2M+', '未知', 'check'),
        'gd'      => array('GD库', '2.0', '2.0+', '未知', 'check'),
        'disk'    => array('磁盘空间', '100M', '不限制', '未知', 'check'),
    );

    // PHP环境检测
    if($items['php'][3] < $items['php'][1]){
        $items['php'][4] = 'times text-warning';
        session('error', true);
    }

    // 附件上传检测
    if(@ini_get('file_uploads'))
        $items['upload'][3] = ini_get('upload_max_filesize');

    // GD库检测
    $tmp = function_exists('gd_info') ? gd_info() : array();
    if(empty($tmp['GD Version'])){
        $items['gd'][3] = '未安装';
        $items['gd'][4] = 'times text-warning';
        session('error', true);
    } else {
        $items['gd'][3] = $tmp['GD Version'];
    }
    unset($tmp);

    // 磁盘空间检测
    if(function_exists('disk_free_space')) {
        $disk_size = floor(disk_free_space(INSTALL_APP_PATH) / (1024*1024));
        $items['disk'][3] = $disk_size.'M';
        if ($disk_size < 100) {
            $items['disk'][4] = 'times text-warning';
            session('error', true);
        }
    }

    return $items;
}

/**
 * 目录，文件读写检测
 * @return array 检测数据
 */
function check_dirfile(){
    $items = array(
        array('dir',  '可写', 'check', '../application'),
        array('dir',  '可写', 'check', '../data'),
        array('dir',  '可写', 'check', '../export'),
        array('dir',  '可写', 'check', '../packet'),
        array('dir',  '可写', 'check', '../plugins'),
        array('dir',  '可写', 'check', './static'),
        array('dir',  '可写', 'check', './uploads'),
        array('dir',  '可写', 'check', '../runtime'),
        array('dir',  '可写', 'check', '../store'),
    );

    foreach ($items as &$val) {
        $item = INSTALL_APP_PATH . $val[3];
        if('dir' == $val[0]){
            if(!is_writable($item)) {
                if(is_dir($item)) {
                    $val[1] = '可读';
                    $val[2] = 'times text-warning';
                    session('error', true);
                } else {
                    $val[1] = '不存在';
                    $val[2] = 'times text-warning';
                    session('error', true);
                }
            }
        } else {
            if(file_exists($item)) {
                if(!is_writable($item)) {
                    $val[1] = '不可写';
                    $val[2] = 'times text-warning';
                    session('error', true);
                }
            } else {
                if(!is_writable(dirname($item))) {
                    $val[1] = '不存在';
                    $val[2] = 'times text-warning';
                    session('error', true);
                }
            }
        }
    }

    return $items;
}

/**
 * 函数检测
 * @return array 检测数据
 */
function check_func(){
    $items = array(
        array('pdo','支持','check','类'),
        array('pdo_mysql','支持','check','模块'),
        array('fileinfo','支持','check','模块'),
        array('curl','支持','check','模块'),
        array('file_get_contents', '支持', 'check','函数'),
        array('mb_strlen', '支持', 'check','函数'),
    );

    foreach ($items as &$val) {
        if(('类'==$val[3] && !class_exists($val[0]))
            || ('模块'==$val[3] && !extension_loaded($val[0]))
            || ('函数'==$val[3] && !function_exists($val[0]))
        ){
            $val[1] = '不支持';
            $val[2] = 'times text-warning';
            session('error', true);
        }
    }

    return $items;
}

/**
 * 写入配置文件
 * @param $config
 * @return array 配置信息
 */
function write_config($config){
    if(is_array($config)){
        //读取配置内容
        $conf = file_get_contents(APP_PATH . 'install/data/database.tpl');
        // 替换配置项
        foreach ($config as $name => $value) {
            $conf = str_replace("[{$name}]", $value, $conf);
        }

        //写入应用配置文件
        if(file_put_contents(APP_PATH . 'database.php', $conf)){
            show_msg('配置文件写入成功');
        } else {
            show_msg('配置文件写入失败！', 'error');
            session('error', true);
        }
        return '';
    }
}

/**
 * 创建数据表
 * @param $db 数据库连接资源
 * @param string $prefix 表前缀
 */
function create_tables($db, $prefix = ''){
    // 读取SQL文件
    $sql = file_get_contents(APP_PATH . 'install/data/dolphin.sql');

    $sql = str_replace("\r", "\n", $sql);
    $sql = explode(";\n", $sql);

    // 替换表前缀
    $orginal = config('original_table_prefix');
    $sql = str_replace(" `{$orginal}", " `{$prefix}", $sql);

    // 开始安装
    show_progress('0%');
    $all_table = config('install_table_total');
    $i = 1;
    foreach ($sql as $value) {
        $value = trim($value);
        if(empty($value)) continue;
        $msg  = (int)($i/$all_table*100) . '%';
        if(false !== $db->execute($value)){
            show_progress($msg);
        } else {
            show_progress($msg, 'error');
            session('error', true);
        }
        $i++;
    }
}

/**
 * 更新数据表
 * @param $db 数据库连接资源
 * @param string $prefix 表前缀
 */
function update_tables($db, $prefix = ''){
    //读取SQL文件
    $sql = file_get_contents(APP_PATH . 'install/data/update.sql');
    $sql = str_replace("\r", "\n", $sql);
    $sql = explode(";\n", $sql);

    // 替换表前缀
    $sql = str_replace(" `dp_", " `{$prefix}", $sql);

    //开始安装
    show_progress('0%');
    $all_table = config('update_data_total');
    $i = 1;
    $msg = '';
    foreach ($sql as $value) {
        $value = trim($value);
        if(empty($value)) continue;
        if(substr($value, 0, 12) == 'CREATE TABLE') {
            $msg  = (int)($i/$all_table*100) . '%';
            if(($db->execute($value)) === false){
                session('error', true);
            }
        } else {
            if(substr($value, 0, 8) == 'UPDATE `') {
                $msg  = (int)($i/$all_table*100) . '%';
            } else if(substr($value, 0, 11) == 'ALTER TABLE'){
                $msg  = (int)($i/$all_table*100) . '%';
            } else if(substr($value, 0, 11) == 'INSERT INTO'){
                $msg  = (int)($i/$all_table*100) . '%';
            }
            if(($db->execute($value)) === false){
                session('error', true);
            }
        }

        if ($msg != '') {
            show_progress($msg);
            $i++;
        }
    }
}

/**
 * 及时显示提示信息
 * @param  string $msg 提示信息
 */
function show_msg($msg, $class = ''){
    echo "<script type=\"text/javascript\">showmsg(\"{$msg}\", \"{$class}\")</script>";
    flush();
    ob_flush();
}

/**
 * 显示进度
 * @param $msg
 * @param string $class
 * @author 蔡伟明 <314013107@qq.com>
 */
function show_progress($msg, $class = ''){
    echo "<script type=\"text/javascript\">show_progress(\"{$msg}\", \"{$class}\")</script>";
    flush();
    ob_flush();
}
/**
 * 获取 IP  地理位置
 * 淘宝IP接口
 * @Return: array
 */
function getCity($ip = '')
{
    if($ip == ''){
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
        $ip=json_decode(file_get_contents($url),true);
        $data = $ip;
    }else{
        $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
        $ip=json_decode(file_get_contents($url));   
        if((string)$ip->code=='1'){
           return false;
        }
        $data = (array)$ip->data;
    }
    
    return $data;   
}
//获取客户端真实IP
function getClientIP()
{
    global $ip;
    if (getenv("HTTP_CLIENT_IP")) {
        $ip = getenv("HTTP_CLIENT_IP");
    } else if (getenv("HTTP_X_FORWARDED_FOR")) {
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    } else if (getenv("REMOTE_ADDR")) {
        $ip = getenv("REMOTE_ADDR");
    } else {
        $ip = "Unknow";
    }

    return $ip;
}